import { defineStore } from 'pinia'
import { ref } from 'vue'

/**
 * 用户状态管理
 */
export const useUserStore = defineStore('user', () => {
    // 基础用户信息
    const userName = ref<string>('访客用户')
    const userEmail = ref<string>('')
    const userAvatar = ref<string>('')
    
    /**
     * 更新用户信息
     */
    const updateUserInfo = (name: string, email?: string, avatar?: string): void => {
        userName.value = name
        if (email) userEmail.value = email
        if (avatar) userAvatar.value = avatar
        
        // 同步保存到本地存储
        try {
            localStorage.setItem('userName', userName.value)
            if (userEmail.value) localStorage.setItem('userEmail', userEmail.value)
            if (userAvatar.value) localStorage.setItem('userAvatar', userAvatar.value)
        } catch (error) {
            console.warn('保存用户信息到本地存储失败:', error)
        }
    }
    
    /**
     * 重置用户信息
     */
    const resetUserInfo = (): void => {
        userName.value = '访客用户'
        userEmail.value = ''
        userAvatar.value = ''
        
        // 清除本地存储
        try {
            localStorage.removeItem('userName')
            localStorage.removeItem('userEmail')
            localStorage.removeItem('userAvatar')
        } catch (error) {
            console.warn('清除本地存储用户信息失败:', error)
        }
    }
    
    /**
     * 从本地存储初始化用户信息
     */
    const initializeFromStorage = (): void => {
        try {
            const storedUserName = localStorage.getItem('userName')
            const storedUserEmail = localStorage.getItem('userEmail')
            const storedUserAvatar = localStorage.getItem('userAvatar')
            
            if (storedUserName) userName.value = storedUserName
            if (storedUserEmail) userEmail.value = storedUserEmail
            if (storedUserAvatar) userAvatar.value = storedUserAvatar
        } catch (error) {
            console.warn('从本地存储加载用户信息失败:', error)
        }
    }

    return {
        // 状态
        userName,
        userEmail,
        userAvatar,
        
        // 方法
        updateUserInfo,
        resetUserInfo,
        initializeFromStorage
    }
})